import {observable, extendObservable, action, toJS} from 'mobx';
import {getDeviceInfo, getDataListInfo, unBindingDeviceInfo} from 'util/api';
import _ from 'lodash';
import {validateFields} from '../Common.js';
import {message} from 'antd';
import store from 'store';

//导出
export default class HouseholdStore {
  constructor() {
    this.reset(true);
  }

  @action
  reset = init => {
    const state = {
      tableData: [],
      loading: false,
      tableParams: {},
      apartmentList: [],
      deviceTypeList: [],
      typeId: '',
      unitId: '',
      deviceId: '',
    };

    if (init) {
      extendObservable(this, state);
    } else {
      Object.keys(state).forEach(key => (this[key] = state[key]));
    }
  };

  @action
  onWillMount = async (location, match, history) => {
    this.reset();

    this.loading = true;
    await this.getDeviceInfo();
    await this.getDataListInfo();
    this.loading = false;
  };

  @action
  getDeviceInfo = async (params = {pageNo: 1, pageSize: 10}) => {
    this.loading = true;
    const res = await getDeviceInfo(params);
    this.loading = false;
    if (res.result === 'success') {
      this.tableParams = {...this.tableParams, ...params};
      this.tableData = res;
    } else {
      message.error(res.msg);
    }
  };
  @action
  changeUnitId = async id => {
    this.my_unitId = id;
  };
  @action
  changeTypeId = async id => {
    this.my_typeId = id;
  };
  @action
  changeDeviceId = async id => {
    this.my_deviceId = id;
  };
  @action
  search = async () => {
    let unitId = this.my_unitId;
    let typeId = this.my_typeId;
    let deviceId = this.my_deviceId;

    this.tableParams = {
      pageNo: 1,
      pageSize: 10,
      ...this.tableParams,
      deviceId,
      typeId,
      unitId,
    };
    this.unitId = unitId;
    this.typeId = typeId;
    this.deviceId = deviceId;
    this.getDeviceInfo(this.tableParams);
  };
  @action
  onUnbundling = async params => {
    const res = await unBindingDeviceInfo(params);
    if (res.result === 'success') {
      this.getDeviceInfo(this.tableParams);
      message.success('解绑成功');
    } else {
      message.success('解绑失败');
    }
  };
  @action
  getDataListInfo = async (params = {}) => {
    const res = await getDataListInfo(params);
    if (res.result === 'success') {
      let apartmentList = res.data.apartmentList;
      let deviceTypeList = res.data.deviceTypeList;
      this.apartmentList = apartmentList.map(item => {
        return {name: item.blockAndUnit, value: item.unitId};
      });
      this.deviceTypeList = deviceTypeList.map(item => {
        return {name: item.deviceType, value: item.typeId};
      });
    } else {
      message.error(res.msg);
    }
  };
}
